package com.example.h9iserver.service.springAi.rag;

import com.example.h9iserver.service.springAi.advisors.ReReadingAdvisor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.RetrievalAugmentationAdvisor;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.rag.retrieval.search.DocumentRetriever;
import org.springframework.ai.rag.retrieval.search.VectorStoreDocumentRetriever;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class RagChatService {

    private String systemMessage = "你是管理IT部门知识库的系统";

    private ChatClient chatClient;

    public RagChatService(ChatClient.Builder builder, VectorStore vectorStore) {
        DocumentRetriever documentRetriever = VectorStoreDocumentRetriever.builder()
                .vectorStore(vectorStore)
                .similarityThreshold(0.6) // 相似度阈值
                .topK(3)
                .build();
        RetrievalAugmentationAdvisor retrievalAugmentationAdvisor = RetrievalAugmentationAdvisor.builder()
                .documentRetriever(documentRetriever)
                .queryAugmenter(LoveAppContextualQueryAugmenterFactory.createInstance())
                .build();
        chatClient = builder
                .defaultAdvisors(
                        retrievalAugmentationAdvisor,
                        new ReReadingAdvisor()
                )
                .defaultSystem(systemMessage)
                .build();
    }

    public void doChatWithRag(String userText) {
        String answer = chatClient.prompt(new Prompt(new UserMessage(userText))).call().content();
        System.out.println("回答：" + answer);
    }

}
